package org.aceor.tennis.web.controller;

import com.google.common.base.Optional;
import org.aceor.tennis.common.domain.User;
import org.aceor.tennis.common.enums.ErrorCode;
import org.aceor.tennis.common.exception.BusinessRuntimeException;
import org.aceor.tennis.service.IUserService;
import org.aceor.tennis.web.dto.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

import static org.aceor.tennis.web.dto.BaseResult.buildError;
import static org.aceor.tennis.web.dto.BaseResult.buildSuccess;
import static org.aceor.tennis.web.util.WebUtil.attainErrorInfoFromBindingResult;


/**
 * Created by lxue on 16/5/14.
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private IUserService<User> userService;

    @RequestMapping(value = "login", method = {RequestMethod.GET})
    public BaseResult<User> login(@ModelAttribute User user) {
        Optional<User> userOptional = userService.login(user);
        if (userOptional.isPresent()) {
            return buildSuccess(userOptional.get());
        } else {
            return buildError(ErrorCode.LOGIN_ERROR, "用户名或密码错误");
        }
    }

    @RequestMapping(value = "register", method = {RequestMethod.POST})
    public BaseResult<User> register(
            @Valid @RequestBody User user,
            BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String error = attainErrorInfoFromBindingResult(bindingResult);
            throw new BusinessRuntimeException(ErrorCode.PARAM_ERROR, error);
        }
        Optional<User> userOptional = userService.register(user);
        if (userOptional.isPresent()) {
            return buildSuccess(userOptional.get());
        } else {
            return buildError(ErrorCode.REGISTER_ERROR);
        }
    }

}
